package util.concurrent;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 6/17/2022 7:30 PM
 */
public class CountDownLatchTest {

    private static final Logger logger = LoggerFactory.getLogger(CountDownLatch.class);

    @Test
    public void test() {
        int num = 12;
        CountDownLatch countDownLatch = new CountDownLatch(num);
        try {
            for (int i = 0; i < num; i++) {
                DemoTask demoTask = new DemoTask(countDownLatch);
                new Thread(demoTask).start();
            }
            countDownLatch.await();
            logger.info("主线程开始...");
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
            Thread.currentThread().interrupt();
        }

    }

    class DemoTask implements Runnable {

        private CountDownLatch countDownLatch;

        DemoTask(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            try {
                // TODO 在这里处理逻辑
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                countDownLatch.countDown();
                logger.info("线程计数器的个数为：{}", countDownLatch.getCount());
            }
        }
    }

}
